package lib.popup

import android.content.Context
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import android.view.Gravity
import android.view.LayoutInflater
import android.view.accessibility.AccessibilityEvent
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.core.CenterPopupView
import com.lxj.xpopup.enums.PopupAnimation
import com.lxj.xpopup.interfaces.SimpleCallback
import lib.popup.databinding.MviPopupMessageBinding

/**
 * author: luoXiong
 * e-mail: 382060748@qq.com
 * date: 2020/10/27 16:58
 * version: 1.0
 * desc:
 */
class _CustomPopupView<V>(context: Context) : CenterPopupView(context) {
    @LayoutRes
    var mCustomLayoutId: Int = 0
    var mOnLayoutCreated: ((V) -> Unit)? = null

    var mOnDismissListener: (() -> Unit)? = null

    private var binding: ViewDataBinding? = null

    fun show(info: PopupCommonInfo) {
        var pwDismissCb: SimpleCallback? = null
        if (mOnDismissListener != null) {
            pwDismissCb = object : SimpleCallback() {
                override fun onDismiss(popupView: BasePopupView) {
                    mOnDismissListener!!.invoke()
                }

                // 如果你自己想拦截返回按键事件，则重写这个方法，返回true即可
                override fun onBackPressed(popupView: BasePopupView): Boolean {
                    return true
                }
            }
        }
        val builder = XPopup.Builder(context)
            .isDestroyOnDismiss(info.isDestroyOnDismiss)
            .dismissOnTouchOutside(info.isDismissOnTouchOutside)
            .dismissOnBackPressed(info.isDismissOnBackPressed)
            .popupAnimation(PopupAnimation.NoAnimation)
            .setPopupCallback(pwDismissCb)
        builder.asCustom(this).show()
    }

    override fun addInnerContent() {
        binding = DataBindingUtil.inflate(
            LayoutInflater.from(context),
            mCustomLayoutId, centerPopupContainer, false
        )
        val params = binding!!.root.layoutParams as LayoutParams
        params.gravity = Gravity.CENTER
        centerPopupContainer.addView(binding!!.root, params)
    }

    override fun onCreate() {
        super.onCreate()
        mOnLayoutCreated?.invoke(binding as V)
    }
    override fun getPopupHeight(): Int {
        return super.getPopupHeight()
    }

    override fun getMaxHeight(): Int {
        return super.getMaxHeight()
        //  return (ScreenUtils.getScreenHeight() * 0.85).toInt()  // 加上后,如果内容高度有5行,有时候也只显示4行,剩下的要滑动,体验不好
    }

}